from django.db import models
from django.forms import ModelForm
from django.core.urlresolvers import reverse
from page.models import Page
from question.models import Question


class Test(Page):
    questions = models.ManyToManyField(Question, through='Contains')
    
    # TODO: Fix this so that it works more dynamically
    # For now is hardcoded with subclass
    def type(self):
        try:
            type = self.progresscheck.type()

        except ProgressCheck.DoesNotExist:
            try:
                type = self.exercise.type()

            except Exercise.DoesNotExist:
                try:
                    type = self.diagnostictest.type()
                except DiagnosticTest.DoesNotExist:
                    type = self.__class__
        
        return type

    def __unicode__(self):
        return self.title+" "+self.content
        
    class Meta:
        db_table = u'tests'

class Exercise(Test):
    def type(self):
        return self.__class__

    class Meta:
        db_table = u'exercises'

class ProgressCheck(Test):
    questions_to_show = models.IntegerField(null=False)

    def type(self):
        return self.__class__

    class Meta:
        db_table = u'progress_checks'

class DiagnosticTest(Test):
    
    def type(self):
        return self.__class__

    class Meta:
        db_table = u'diagnostic_tests'

class Contains(models.Model):
    question = models.ForeignKey(Question)
    test = models.ForeignKey(Test)
    question_order = models.IntegerField(null=True, blank=True, unique=False)

    class Meta:
        db_table = u'contains'
    
class ActiveDiagnosticTest(models.Model):
    diagnostic_test = models.ForeignKey(DiagnosticTest, null=True, blank=True)

    class Meta:
        db_table = u'active_diagnostic_test'
    
